<?php


namespace app\portal\model;

use think\db\Query;
use think\Model;
use tree\Tree;

class ContestModel extends Model
{
    /**
     * 模型名称
     * @var string
     */
    protected $name = 'contest';

    protected $type = [
        'more' => 'array',
    ];

    /**
     * 赛事查询
     * @param      $filter
     * @param bool $isPage
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function adminContestList($filter, $isPage = false)
    {

        $field = 'a.*,u.user_login,u.user_nickname,u.user_email';

        $portalPostModel = new PortalPostModel();
        $contestModel = new ContestModel();
        $contestQuery   = $contestModel->alias('a');
        $contestQuery->join('user u', 'a.user_id = u.id');

        $category = empty($filter['category']) ? 0 : intval($filter['category']);
        if (!empty($category)) {
            $contestQuery->join('contest_category_post b', 'a.id = b.contest_id');
            $field = 'a.*,b.id AS contest_category_id,b.list_order,b.category_id,u.user_login,u.user_nickname,u.user_email';
        }

        $contests = $contestQuery->field($field)
            ->where('a.delete_time', 0)
            ->where(function (Query $query) use ($filter, $isPage) {

                $category = empty($filter['category']) ? 0 : intval($filter['category']);
                if (!empty($category)) {
                    $query->where('b.category_id', $category);
                }

                $appleStart = empty($filter['apple_start']) ? 0 : strtotime($filter['apple_start']);
                $appleEnd   = empty($filter['apple_end']) ? 0 : strtotime($filter['apple_end']);
                if (!empty($appleStart)) {
                    $query->where('a.apple_start', '>=', $appleStart);
                }
                if (!empty($appleEnd)) {
                    $query->where('a.apple_end', '<=', $appleEnd);
                }

                $reviewStart = empty($filter['review_start']) ? 0 : strtotime($filter['review_start']);
                $reviewEnd   = empty($filter['review_end']) ? 0 : strtotime($filter['review_end']);
                if (!empty($reviewStart)) {
                    $query->where('a.review_start', '>=', $reviewStart);
                }
                if (!empty($reviewEnd)) {
                    $query->where('a.review_end', '<=', $reviewEnd);
                }

                $keyword = empty($filter['keyword']) ? '' : $filter['keyword'];
                if (!empty($keyword)) {
                    $query->where('a.title', 'like', "%$keyword%");
                }
            })
            ->order('update_time', 'DESC')
            ->paginate(10);

        return $contests;

    }

    /**
     * 获取赛事列表
     * @param $filter
     * @return mixed
     */
    public function getContestList($filter) {
        $contestList = array();
        $contestList = $this->alias('c')
                        ->join('contest_category cc', 'c.category_id = cc.id')
                        ->where('c.delete_time',0)
                        ->order('c.status','DESC')
                        ->order('c.update_time', 'DESC')
                        ->field('c.*,cc.name')
                        ->where(function (Query $query) use ($filter) {

                            $category = empty($filter['category']) ? 0 : intval($filter['category']);
                            if (!empty($category)) {
                                $query->where('c.category_id', $category);
                            }

                            $appleStart = empty($filter['apple_start']) ? 0 : strtotime($filter['apple_start']);
                            $appleEnd   = empty($filter['apple_end']) ? 0 : strtotime($filter['apple_end']);
                            if (!empty($appleStart)) {
                                $query->where('c.apple_start', '>=', $appleStart);
                            }
                            if (!empty($appleEnd)) {
                                $query->where('c.apple_end', '<=', $appleEnd);
                            }

                            $reviewStart = empty($filter['review_start']) ? 0 : strtotime($filter['review_start']);
                            $reviewEnd   = empty($filter['review_end']) ? 0 : strtotime($filter['review_end']);
                            if (!empty($reviewStart)) {
                                $query->where('c.review_start', '>=', $reviewStart);
                            }
                            if (!empty($reviewEnd)) {
                                $query->where('c.review_end', '<=', $reviewEnd);
                            }

                            $keyword = empty($filter['keyword']) ? '' : $filter['keyword'];
                            if (!empty($keyword)) {
                                $query->where('c.keywords', 'like', "%$keyword%");
                            }
                        })
                        ->paginate(10);

        return $contestList;
    }

    /**
     * admin新增赛事
     * @param $data
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function adminAddContest($data, $categories) {
        $data['user_id'] = cmf_get_current_admin_id();

        if (!empty($data['picture'])) {
            $data['picture'] = cmf_asset_relative_url($data['picture']);
        }
        // 修改赛事状态
        if(isset($data['status'])) {
            if($data['status'] == 1) {
                $res = $this->where('status',1)->find();
                if(!empty($res)) {
                    $this->where('id',$res['id'])->update(['status'=>0]);
                }
            }
        } else {
            $data['status'] = 0;
        }

        $data['apple_start'] = strtotime($data['apple_start']);
        $data['apple_end'] = strtotime($data['apple_end'])+86399;
        $data['review_start'] = strtotime($data['review_start']);
        $data['review_end'] = strtotime($data['review_end'])+86399;
        $this->save($data);
        if (is_string($categories)) {
            $categories = explode(',', $categories);
        }

        $this->categories()->save($categories);
        return $this;
    }

    /**
     * 关联分类表
     * @return \think\model\relation\BelongsToMany
     */
    public function categories()
    {
        return $this->belongsToMany('ContestCategoryModel', 'contest_category_post', 'category_id', 'contest_id');
    }

    /**
     * admin编辑赛事
     * @param $data
     * @return $this
     */
    public function adminEditContest($data, $categories) {
        // 缩略图url
        if (!empty($data['picture'])) {
            $data['picture'] = cmf_asset_relative_url($data['picture']);
        }
        // 更新赛事状态
        if(isset($data['status'])) {
            if($data['status'] == 1) {
                $res = $this->where('status',1)->find();
                if(!empty($res)) {
                    $this->where('id',$res['id'])->update(['status'=>0]);
                }
            }
        } else {
            $data['status'] = 0;
        }
        // 处理时间小于0
        if(strtotime($data['apple_start']) > 0) {
            $data['apple_start'] = strtotime($data['apple_start']);
        }
        else {
            $data['apple_start'] = time();
        }
        if(strtotime($data['apple_end']) > 0) {
            $data['apple_end'] = strtotime($data['apple_end']);
        }
        else {
            $data['apple_end'] = time();
        }
        if(strtotime($data['review_start']) > 0) {
            $data['review_start'] = strtotime($data['review_start']);
        }
        else {
            $data['review_start'] = time();
        }
        if(strtotime($data['review_end']) > 0) {
            $data['review_end'] = strtotime($data['review_end']);
        }
        else {
            $data['review_end'] = time();
        }
        $contest = self::find($data['id']);

        $contest->save($data);

        if (is_string($categories)) {
            $categories = explode(',', $categories);
        }

        $oldCategoryIds        = $contest->categories()->column('category_id');
        $sameCategoryIds       = array_intersect($categories, $oldCategoryIds);
        $needDeleteCategoryIds = array_diff($oldCategoryIds, $sameCategoryIds);
        $newCategoryIds        = array_diff($categories, $sameCategoryIds);

        if (!empty($needDeleteCategoryIds)) {
            $contest->categories()->detach($needDeleteCategoryIds);
        }

        if (!empty($newCategoryIds)) {
            $contest->categories()->attach(array_values($newCategoryIds));
        }

        return $this;
    }
}